//
//  KDMessagePushController.m
//  YuQingXiaoFang
//
//  Created by wangdongdong on 18/5/17.
//  Copyright © 2018年 KDTech. All rights reserved.
//

#import "KDMessagePushController.h"
#import "KDMessagePushListCell.h"
#import "KDMessagePushListCellModel.h"
#import "KDBaseListParam.h"

#import "KDTabBarController.h"
#import "KDDetailsubscribController.h"
#import "KDSubscripRequestTool.h"
#import "KDSubscribeListParam.h"
#import "KDMessagePushRequestTool.h"

#import "KDCollectRequestTool.h"
#import "KDMoveFavorParam.h"
@interface KDMessagePushController ()<UITableViewDelegate,UITableViewDataSource,KDMessagePushListCellDelegate,KDDetailSubscribControllerDelegate>

/**
 *  所有主题数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**  <#Description#> */
@property (nonatomic, strong) NSArray *infoArr;
/**  <#Description#> */
@property (nonatomic, weak) UITableView *currentTabV;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;

@end
static CGFloat const tableViewH = 75;

@implementation KDMessagePushController
#pragma mark - 懒加载区
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
#pragma mark -生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavBar];
    [self setUpTableView];}
#pragma mark - 板块布置区
- (void)setUpTableView
{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, self.view.height -64) style:UITableViewStylePlain];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = tableViewH;
    if (!iOS7) {
        tableView.estimatedRowHeight = tableViewH;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    UINib *xib =[UINib nibWithNibName:@"KDMessagePushListCell" bundle:nil] ;
    
    [tableView registerNib:xib forCellReuseIdentifier:@"KDMessagePushListCell"];
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
- (void)setupNavBar{
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect_add"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    
}
#pragma mark - 事件点击区
- (void)leftItemClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 网络请求区
- (void)loadDetailData{
    
    KDMessagePushListParam *param = [[KDMessagePushListParam alloc]init];
    param.limit = @"20";
    self.page = @"1";
    param.page = self.page;
    [KDMessagePushRequestTool getMesasgePushListWithParam :param success:^(KDGetMessagePushListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.infoArr = responseObejct.data;
            
            [self.currentTabV.header endRefreshing];
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.header endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
- (void)loadMoreDetailData{
    WS(ws);
    KDMessagePushListParam *param = [[KDMessagePushListParam alloc]init];
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    param.page = self.page;
    
    param.limit = @"20";
    [KDMessagePushRequestTool getMesasgePushListWithParam:param success:^(KDGetMessagePushListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            NSArray *arr1 = responseObejct.data;
            if (arr1.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
                [arr addObjectsFromArray:arr1];
                self.infoArr = arr;
                [self.currentTabV.footer endRefreshing];
                [self.currentTabV reloadData];
            }else{
                [self.currentTabV.footer noticeNoMoreData];
            }
            
            
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.footer endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
#pragma mark - 通知接收区
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDMessagePushListCell *cell = [KDMessagePushListCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.model = self.infoArr[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}


 /**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDMessagePushListCell *cell = (KDMessagePushListCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        WS(ws);
        [self getNewsModelWithID:cell.model.newsId success:^(KDSubscribCellModel *model) {
            KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
            singleCtrl.delegate = ws;
            singleCtrl.model = model;
            
            //            self.hidesBottomBarWhenPushed = YES;
            [ws.navigationController pushViewController:singleCtrl animated:YES];
            //            self.hidesBottomBarWhenPushed = NO;
        }];

    }
}

/**
 *  通过ID，请求获取一个本信息的所有细节
 *
 *  @param ID 信息ID
 */
- (void)getNewsModelWithID:(NSString *)ID success:(void (^)(KDSubscribCellModel *model))success{
    
    KDMoveFavorParam *param = [[KDMoveFavorParam alloc]init];
    param.ID = ID;
    [SVProgressHUD showWithStatus:@"加载中…" maskType:SVProgressHUDMaskTypeGradient];
    [KDCollectRequestTool getNewsWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            KDSubscribCellModel * model= [KDSubscribCellModel objectWithKeyValues:responseObejct.data];
            [SVProgressHUD dismiss];
            if (model) {
                success(model);
            }else{
                [SVProgressHUD showInfoWithStatus:@"未查询到数据" maskType:SVProgressHUDMaskTypeGradient];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
